#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
大乐透模型训练脚本
一键训练大乐透的基础LSTM模型和增强版LSTM-CRF模型
"""

import os
import sys
import subprocess
from datetime import datetime

def run_script(script_path):
    """运行Python脚本"""
    print(f"[RUN] 正在运行: {script_path}")
    try:
        # 使用当前Python解释器运行脚本
        result = subprocess.run([sys.executable, script_path], 
                              capture_output=True, text=True, encoding='utf-8')
        
        # 输出标准输出和错误输出
        if result.stdout:
            print(result.stdout)
        if result.stderr:
            print(result.stderr, file=sys.stderr)
            
        if result.returncode == 0:
            print(f"[OK] {script_path} 运行成功")
            return True
        else:
            print(f"[ERROR] {script_path} 运行失败，返回码: {result.returncode}")
            return False
    except Exception as e:
        print(f"[ERROR] 运行 {script_path} 时出错: {e}")
        return False

def train_dlt_models():
    """训练大乐透模型"""
    print("[START] 开始训练大乐透模型")
    print("=" * 60)
    
    # 获取项目根目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    
    # 定义脚本路径
    fetch_data_script = os.path.join(current_dir, 'scripts', 'dlt', 'fetch_dlt_data.py')
    train_lstm_script = os.path.join(current_dir, 'scripts', 'dlt', 'train_dlt_model.py')
    train_enhanced_script = os.path.join(current_dir, 'scripts', 'dlt', 'train_enhanced_lstm_crf.py')
    
    # 检查必要文件是否存在
    scripts_to_check = [
        ("数据采集脚本", fetch_data_script),
        ("基础LSTM训练脚本", train_lstm_script),
        ("增强版LSTM-CRF训练脚本", train_enhanced_script)
    ]
    
    for name, path in scripts_to_check:
        if not os.path.exists(path):
            print(f"[ERROR] {name}不存在: {path}")
            return False
        print(f"[CHECK] {name}存在: {path}")
    
    print()
    
    # 1. 采集数据
    print("[STEP 1] 采集大乐透历史数据")
    if not run_script(fetch_data_script):
        print("[ERROR] 数据采集失败")
        return False
    print()
    
    # 2. 训练基础LSTM模型
    print("[STEP 2] 训练大乐透基础LSTM模型")
    if not run_script(train_lstm_script):
        print("[ERROR] 基础LSTM模型训练失败")
        return False
    print()
    
    # 3. 训练增强版LSTM-CRF模型
    print("[STEP 3] 训练大乐透增强版LSTM-CRF模型")
    if not run_script(train_enhanced_script):
        print("[ERROR] 增强版LSTM-CRF模型训练失败")
        return False
    print()
    
    return True

def main():
    """主函数"""
    print("[TARGET] 大乐透模型训练程序")
    print(f"[TIME] 开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print()
    
    success = train_dlt_models()
    
    print()
    if success:
        print("[SUCCESS] 所有模型训练完成！")
        print("现在可以使用大乐透💎 LSTM-CRF 经典模式增强版进行预测了。")
    else:
        print("[FAIL] 模型训练失败！")
    
    print(f"[TIME] 结束时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

if __name__ == "__main__":
    main()